package com.vx.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.vx.ratingTool.Player;
import com.vx.ratingTool.bo.PlayerBOimpl;
import com.vx.ratingTool.dao.PlayerDAOimpl;
import com.vx.ratingTool.match.Match;
import com.vx.ratingTool.match.MatchFinder;

@Controller
@RequestMapping("/simulateSingleRandomMatch")
public class SimulateSingleMatchController {

	private PlayerDAOimpl playerDAO;
	private PlayerBOimpl playerBO;

	public PlayerDAOimpl getPlayerDAOimpl() {
		return playerDAO;
	}

	@Autowired
	public void setPlayerDAOimpl(PlayerDAOimpl playerDAO) {
		this.playerDAO = playerDAO;
	}

	public PlayerBOimpl getPlayerBO() {
		return playerBO;
	}

	@Autowired
	public void setPlayerBO(PlayerBOimpl playerBO) {
		this.playerBO = playerBO;
	}

	private List<Player> players;

	@RequestMapping(method = RequestMethod.GET)
	public String CreatePlayers(Model model) {
		Random rnd = new Random();

		List<Player> dataBaseList = playerBO.GetListOfPlayers();
		List<Player> playerPoolList = new ArrayList<Player>();
		for (int i = 0; i < 200; i++) {
			playerPoolList.add(dataBaseList.get(rnd.nextInt(dataBaseList.size())));
		}

		Player newPlayer = playerBO.findById(rnd.nextInt(playerBO.GetListOfPlayers().size()));
		playerPoolList.add(newPlayer);

		MatchFinder MF = new MatchFinder(playerPoolList, newPlayer, 50, 50);
		Match M = MF.findMatch();
		List<Player> foundList = new ArrayList<Player>(MF.getFoundPlayers());
		model.addAttribute("foundPlayers", foundList);
		M.Simulate();

		List<Player> updList = new ArrayList<Player>(M.getTeamA());
		playerBO.massUpdate(updList);
		updList = new ArrayList<Player>(M.getTeamB());
		playerBO.massUpdate(updList);

		model.addAttribute("teamAplayers", M.getTeamA());
		model.addAttribute("teamBplayers", M.getTeamB());
		model.addAttribute("teamAskill", M.getTeamAskill());
		model.addAttribute("teamBskill", M.getTeamBskill());
		model.addAttribute("teamArating", M.getTeamArating());
		model.addAttribute("teamBrating", M.getTeamBrating());
		model.addAttribute("teamAchance", M.getChanceToWinOfTeamAInPercent());
		model.addAttribute("teamAchanceRating", M.getChanceToWinOfTeamABasedOnRatingPercent());
		if (M.getTeamAwins())
			model.addAttribute("teamAwins", "Team A");
		else
			model.addAttribute("teamAwins", "Team B");

		return "simulateSingleRandomMatch";
	}
}
